function initEnv() {
	if(DWZ.user.isLogin()){
		$("#layout").show();
	}
	
	if ( $.browser.msie && /6.0/.test(navigator.userAgent) ) {
		try {
			document.execCommand("BackgroundImageCache", false, 1);	
		}catch(e){	
		}
	}
	initLayout();
	$(window).resize(function(){
		clearTimeout(DWZ.resizeTime);
		$this=$(this);
		DWZ.resizeTime = setTimeout(function(){
			clearTimeout(DWZ.resizeTime);
			initLayout();
			$this.trigger("resizeGrid");
		},10);
	});

	$("#leftside").jBar({minW:150, maxW:700});
	
	if ($.taskBar) $.taskBar.init();
	if (navTab) navTab.init();
	$("#switchEnvBox").switchEnv();
	initAccount();
	initUI();

	$("#taskbar li").hoverClass("hover");
	$("#taskbar li.selected").hoverClass("selectedHover");
	$("#taskbar .close").hoverClass("closeHover");
	$("#taskbar .restore").hoverClass("restoreHover");
	$("#taskbar .minimize").hoverClass("minimizeHover");
	$("#taskbar .taskbarLeft").hoverClass("taskbarLeftHover");
	$("#taskbar .taskbarRight").hoverClass("taskbarRightHover");
	
	// tab styles
	var jTabsPH = $("div.tabsPageHeader");
	jTabsPH.find(".tabsLeft").hoverClass("tabsLeftHover");
	jTabsPH.find(".tabsRight").hoverClass("tabsRightHover");
	jTabsPH.find(".tabsMore").hoverClass("tabsMoreHover");
	
	DWZ.ajaxbg=$("#background,#progressBar");

	setTimeout(function(){
		DWZ.ajaxbg.hide().ajaxStart(function(){
			//DWZ.ajaxbg.show();
		}).ajaxStop(function(){
			if($.active<=0){
				//DWZ.hidebg();
			}
		});
	}, 500);
}
function initAccount(){
	if(DWZ.user.isLogin()){
		var account=$("#headerAccountInfo").show();
		$("span[name=role]",account).text(DWZ.user.rolename);
		$("span[name=account]",account).text(DWZ.user.username);
		$("a[name=changepwd]",account).attr("url","account/account_update.html?user_id="+DWZ.user.userId);
	}
}

function ajaxCallback($this,json){
	var callback=$this.attr("callback");
	if(!callback) return;
	if(callback=="reload"){
		//DWZ.loadPageContent($this);
		var list=$this.parents('.panelBar').next("div.tableList").find('>table.list');
		if(list.length==0)
			list=$this.parents("table.list");
		if(list.length==0)
			list=$this.parents('.panelBar').next('>table.list');
			
		
		if(list.length==0)
			DWZ.loadPageContent($this);
		else if(list.first().parents("table.list").length>0){
			list.first().removeAttr('loaded').jBinds();
		}else{
			$panel=navTab.getCurrentPanel();
			panelLoaded($panel.children(".page"));
		}
	}else if(callback=="reloadpage"){
		DWZ.loadPageContent($this);
	}else if(callback.indexOf("$this")>=0){
		try{
			var func=new Function("$this",callback);
			func($this);
		}catch(e){
			alert("执行【"+callback+"】时发生错误。错误码："+(e.number & 0xFFFF)+"，"+e.description);
		}
	}else if(/\(.*\)/.test(callback)){
		$callback = callback.replace(/\(.*\)/,function($1){
			return $1.replace("data","json").replace("this","$this");
		})
		try{
			eval('(' + $callback + ')');
		}catch(e){
			alert("执行【"+callback+"】时发生错误。错误码："+(e.number & 0xFFFF)+"，"+e.description);
		}
	}else{
		try{
			var $callback = eval('(' + callback + ')');
			$callback(json,$this);
		}catch(e){
			alert("执行【"+callback+"】时发生错误。错误码："+(e.number & 0xFFFF)+"，"+e.description);
		}
	}
}

function initLayout(){
	var iContentW = $(window).width() - (DWZ.ui.sbar ? $("#sidebar").width() + 10 : 34) - 5;
	//var iContentH = $(window).height() - $("#header").height() - 34;
	var iContentH = $(window).height() - $("#header").height();

	$("#container").width(iContentW);
	$("#container .tabsPageContent").height(iContentH - 34).find("[layoutH]").layoutH();
	$("#sidebar, #sidebar_s .collapse, #splitBar, #splitBarProxy").height(iContentH - 7).bind("contextmenu selectstart",new Function("event.returnValue=false;"));
	//$("#sidebar, #sidebar_s .collapse, #splitBar, #splitBarProxy").bind("contextmenu selectstart",new Function("event.returnValue=false;"));
	$("#taskbar").css({top: iContentH + $("#header").height() + 5, width:$(window).width()});
}

function initTable(jP){
	var jParent = jP || $(document);
	//tables
	
	$("table.table", jParent).jTable();
	
	// css tables
	$('table.list', jParent).cssTable();
	//$('table.list>tbody>tr', jParent).hover(function(){
	//	$(this).addClass('hover');
	//}, function(){
	//	$(this).removeClass('hover');
	//}).each(function(index){
	//	if (index % 2 == 1) $(this).addClass("trbg");
	//});
}

function initUI(jP){
	var jParent = $(jP || document);

	//tables bind data
	$("table.list,table.table", jParent).jBinds(function(){initTable(jParent)});

	initTable(jParent);

	//auto bind tabs
	$("div.tabs", jParent).each(function(){
		var $this = $(this);
		var options = {};
		options.currentIndex = $this.attr("currentIndex") || 0;
		options.eventType = $this.attr("eventType") || "click";
		$this.tabs(options);
	});

	$('div.accordion', jParent).each(function(){
		var $this = $(this);
		var active=$(">div[default=true]",this).length;
		$this.accordion({fillSpace:$this.attr("fillSpace"),alwaysOpen:true,active:active,action:$this.attr("action")});//,action:$this.attr("action")
	});
	
	$("ul.tree:not('.noload')", jParent).each(function(){
		var $this = $(this);
		$this.bindTree();
	});
	
	//$("ul.tree", jParent).jTree();//.find("li>div")._contextmenu();

	$(":button.checkboxCtrl, :checkbox.checkboxCtrl").checkboxCtrl(jParent);
	
	//$("select.combox",jParent).combox();
	
	if ($.fn.xheditor) {
		$("textarea.editor", jParent).each(function(){
			var $this = $(this);
			var tools = $this.attr("tools");
			if(tools){
				try{
					tools=eval("("+tools+")");
					$this.xheditor(tools);
				}catch(e){
					alert("错误："+tools);
				}
			}else{
				$this.xheditor({skin: 'vista'});
			}
		});
	}
	if ($.fn.uploadify) {
		$(":file[uploader]", jParent).each(function(){
			var $this = $(this);
			var options = {
				uploader: $this.attr("uploader"),
				script: $this.attr("script"),
				cancelImg: $this.attr("cancelImg"),
				queueID: $this.attr("fileQueue") || "fileQueue",
				fileDesc: "*.jpg;*.jpeg;*.gif;*.png;*.pdf",
				fileExt : "*.jpg;*.jpeg;*.gif;*.png;*.pdf",
				folder	: $this.attr("folder"),
				auto: true,
				multi: true,
				onError:uploadifyError,
				onComplete: uploadifyComplete,
				onAllComplete: uploadifyAllComplete
			};
			if ($this.attr("onComplete")) {
				options.onComplete = DWZ.jsonEval($this.attr("onComplete"));
			}
			if ($this.attr("onAllComplete")) {
				options.onAllComplete = DWZ.jsonEval($this.attr("onAllComplete"));
			}
			if ($this.attr("scriptData")) {
				options.scriptData = DWZ.jsonEval($this.attr("scriptData"));
			}
			$this.uploadify(options);
		});
	}
	
	// init styles
	$("input[type=text], input[type=password], textarea", jParent).addClass("textInput").focusClass("focus");

	$("input[readonly], textarea[readonly]", jParent).addClass("readonly");
	$("input[disabled=true], textarea[disabled=true]", jParent).addClass("disabled");

	$("input[type=text]", jParent).not("div.tabs input[type=text]", jParent).filter("[alt]").inputAlert();
	$("input[focus=true], textarea[focus=true]",jParent).focus();

	//Grid ToolBar
	$("div.panelBar li, div.panelBar", jParent).hoverClass("hover");
		
	//Button
	$("div.button", jParent).hoverClass("buttonHover");
	$("div.buttonActive", jParent).hoverClass("buttonActiveHover");
	
	//tabsPageHeader
	$("div.tabsHeader li, div.tabsPageHeader li, div.accordionHeader, div.accordion", jParent).hoverClass("hover");
	
	$("div.panel", jParent).jPanel();

	//validate form
	$("form.required-validate", jParent).each(function(){
		$(this).validate({
			focusInvalid: false,
			focusCleanup: true,
			errorElement: "label",
			ignore:".ignore",
			invalidHandler: function(form, validator) {
				return;
				var errors = validator.numberOfInvalids();
				if (errors) {
					var message = DWZ.msg("validateFormError",[errors]);
					alertMsg.error(message);
				} 
			}
		});
	});

	if ($.fn.datepicker){
		$('input.date', jParent).each(function(){
			var $this = $(this);
			var opts = {};
			if ($this.attr("datefmt")) opts.pattern = $this.attr("datefmt");
			if ($this.attr("mindate")) opts.minDate = $this.attr("mindate");
			if ($this.attr("maxdate")) opts.maxDate = $this.attr("maxdate");
			if ($this.attr("yearstart")) opts.yearstart = $this.attr("yearstart");
			if ($this.attr("yearend")) opts.yearend = $this.attr("yearend");
			if ($this.attr("mmstep")) opts.mmStep = $this.attr("mmstep");
			if ($this.attr("ssstep")) opts.ssStep = $this.attr("ssstep");
			$this.datepicker(opts);
		});
	}

	// navTab
	$("a[target=navTab]", jParent).each(function(){
		$(this).unbind("click").click(function(event){
			var $this = $(this);
			var title = $this.attr("title") || $this.text();
			var tabid = $this.attr("rel") || "_blank";
			var flesh = eval($this.attr("flesh") || "false");
			var url = unescape($this.attr("url")||$this.attr("href")).replaceTmById(jParent);
			
			if(!url) return;
			
			DWZ.debug(url);
			if (!url.isFinishedTm()) {
				alertMsg.error($this.attr("warn") || DWZ.msg("alertSelectMsg"));
				return false;
			}
			navTab.openTab(tabid, url,{title:title, flesh:flesh});

			event.preventDefault();
		});
	});
	// navTabTodo
	$("a[target=navTabTodo]", jParent).each(function(){
		$(this).unbind("click").click(function(event){
			var $this = $(this);
			var area=$this.attr("area");
			var pageContent=DWZ.getPageContent($this);
			//var url = unescape($this.attr("href")).replaceTmById(jParent);
			var action=$this.attr("url")||$this.attr("href");
			var url = unescape(action).replaceTmByName(area?$(area,pageContent):pageContent);
			//DWZ.debug(url);
			if (!url.isFinishedTm()) {
				alertMsg.error($this.attr("warn") || DWZ.msg("alertSelectMsg"));
				return false;
			}
			
			var callback=function(json){
				ajaxCallback($this,json);
			}
			
			var title = $this.attr("title");
			if (title) {
				alertMsg.confirm(title, {
					okCall: function(){
						navTabTodo(url,{
								callback: callback,
								data:$this.data("data"),
								type:$this.attr("type")
							});
					}
				});
			} else {
				navTabTodo(url,{
						callback: callback,
						data:$this.data("data"),
						type:$this.attr("type")
					});
			}
			event.preventDefault();
		});
	});
	
	//dialogs
	$("a[target=dialog]", jParent).each(function(){
		$(this).unbind("click").click(function(event){
			var $this = $(this);
			var title = $this.attr("title") || $this.text();
			if(!$this.attr("rel")) $this.attr("rel","dlg"+new Date().getTime());
			var rel = $this.attr("rel") || "_blank";
			var options = {};
			var w = $this.attr("width");
			var h = $this.attr("height");
			if (w) options.width = w;
			if (h) options.height = h;
			options.max = eval($this.attr("max") || "false");
			options.mask = eval($this.attr("mask") || "false");
			options.maxable = eval($this.attr("maxable") || "true");
			options.minable = eval($this.attr("minable") || "true");
			options.flesh = eval($this.attr("flesh") || "true");
			options.resizable = eval($this.attr("resizable") || "true");
			options.drawable = eval($this.attr("drawable") || "true");
			options.close = eval($this.attr("close") || "");
			options.param = $this.attr("param") || "";
			options.iframe=eval($this.attr("iframe") || "false");
			options.event=event;
			
			var url = unescape($this.attr("url")||$this.attr("href")).replaceTmById(jParent);
			//DWZ.debug(url);
			if (!url.isFinishedTm()) {
				alertMsg.error($this.attr("warn") || DWZ.msg("alertSelectMsg"));
				return false;
			}
			
			var callback=function(json){
				ajaxCallback($this,json);
			}
			
			$.pdialog.open(url, rel, title, options,callback);
			
			return false;
		});
	});
	$("a[target=ajax]", jParent).each(function(){
		$(this).unbind("click").click(function(event){
			var $this = $(this);
			
			var callback=function(json){
				ajaxCallback($this,json);
			}
			
			var url = $this.attr("url")||$this.attr("href");
			
			var rel = $this.attr("rel");
			if (rel){
				var container=$("#"+rel);
				if(container[0].tagName.toLowerCase()=="td")
					container.parent().show();
				
			 	if(url)
			 		container.loadUrl(url,callback);
			 	else{
			 		//DWZ.get(url,function(){
			 			callback();
			 		//})
			 	}
			}else{
				if(url){
					DWZ.get(url,function(){
			 			callback();
			 		})
				}else{
					callback();
				}
			}
			event.preventDefault();
		});
	});
	
	$("a[target=load]", jParent).each(function(){
		$(this).unbind("click").click(function(event){
			var $this = $(this);
			
			var callback=function(json){
				ajaxCallback($this,json);
			}
			
			var url = $this.attr("url")||$this.attr("href");
			
			var rel = $this.attr("rel");
//			if (rel){
				var container=rel?$("#"+rel):$this.parents("tr:eq(0)").next("tr.hide").find(">td");
			 	
		 		if($this.hasClass("collapsable")){
					$this.parents("tbody.list").eq(0).find(">tr>td>div>a.expand").click();
		 			
					$this.removeClass("collapsable").addClass("expand");
					if(url)
				 		container.loadUrl(url,callback);
				 	else{
				 		callback();
				 	}
					
//					container.parent().show();
					container.parent().animate({
					   height: 'toggle', opacity: 'toggle'
					 }, "slow");
//					container.parent().animate({height: "show"});
					
					var cache = $this.attr("cache");
					if(cache!=="false") $this.removeAttr('url');
					
				}else{
					$this.removeClass("expand").addClass("collapsable");
					container.parent().hide();
				}
//			}else{
//				if(url){
//					DWZ.get(url,function(){
//			 			callback();
//			 		})
//				}else{
//					callback();
//				}
//			}
			event.preventDefault();
		});
	});
	
//	$("a",jParent).mouseover(function(){
//		var $this=$(this);
//		window.status=$this.attr("url")||$this.attr("href");
//	});
	
	$("div.pagination", jParent).each(function(){
		var $this = $(this);
		$this.pagination({
			targetType:$this.attr("targetType"),
			totalCount:$this.attr("totalCount"),
			numPerPage:$this.attr("numPerPage"),
			pageNumShown:$this.attr("pageNumShown"),
			currentPage:$this.attr("currentPage")
		});
	});
	
	$("#uploadOneFile").each(function(){
		var $this = $(this);
		$this.removeAttr("id");
		var title=$this.text();
		var param=$this.attr("param");
		var swfButton="<a class='btn'><span><div id='uploadOneFile'>"+title+"</div></span></a>";
		var progress='<div id="progressArea"><div id="progressBar"><span>0%</span><div id="progress" style="width:1px;"></div></div></div>';
	});

	//鼠标经过显示区域(tips)效果
	$('img[alt],img[title]', jParent).tips();
	return;
	//更多搜索按钮
	jParent.find(".searchBar .more").toggle(function(){
		$(this).removeClass("moreExpandable").addClass("moreCollapsable");
		//jParent.find(".searchBar .searchContent").css("overflow","hidden");
		jParent.find(".pageContent>.tableList").attr("layouth",90);
		jParent.find(".searchBar .searchContent").animate( { height: "25px"}, 500 ,initLayout );
	},function(){
		$(this).removeClass("moreCollapsable").addClass("moreExpandable");
		//jParent.find(".searchBar .searchContent").css("overflow","visible");
		var height=jParent.find(".searchBar .searchContent .fields").height()||jParent.find(".searchBar .searchContent .fields")[0].scrollHeight;
		if(height<25*2) return;
		jParent.find(".pageContent>.tableList").attr("layouth",65+height);
		jParent.find(".searchBar .searchContent").animate( { height: height+"px"}, 500 ,initLayout);

		//alert(jParent.find(".searchBar .searchContent").height());
		//alert(jParent.find(".searchBar .searchContent .fields").height());
	});
}

